package com.wenzhoujie.service;

import java.io.File;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.View;
import android.widget.RemoteViews;

import com.alibaba.fastjson.JSON;
import com.wenzhoujie.library.dialog.SDDialogConfirm;
import com.wenzhoujie.library.dialog.SDDialogCustom;
import com.wenzhoujie.library.dialog.SDDialogCustom.SDDialogCustomListener;
import com.wenzhoujie.library.dialog.SDDialogManager;
import com.wenzhoujie.library.utils.SDPackageUtil;
import com.wenzhoujie.library.utils.SDToast;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.util.OtherUtils;
import com.lingou.www.R;
import com.wenzhoujie.app.App;
import com.wenzhoujie.common.HttpManagerX;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.act.InitActUpgradeModel;
import com.wenzhoujie.utils.SDInterfaceUtil;

/**
 * 更新服务
 * 
 * @author yhz
 */
public class AppUpgradeService extends Service
{
	public static final String EXTRA_SERVICE_START_TYPE = "extra_service_start_type";
	private static final int DEFAULT_START_TYPE = 0;
	private int mStartType = DEFAULT_START_TYPE; // 0代表启动app时候程序自己检测，1代表用户手动检测版本
	public static final int mNotificationId = 100;
	private String mDownloadUrl = null;
	private NotificationManager mNotificationManager = null;
	private Notification mNotification = null;
	private PendingIntent mPendingIntent = null;
	private int mServerVersion = 0;
	private String mFileName = null;
	private boolean mIsForceUpgrade = false;

	@Override
	public IBinder onBind(Intent intent)
	{
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId)
	{
		getIntentData(intent);
		requestCheckVersion();
		return super.onStartCommand(intent, flags, startId);
	}

	private void getIntentData(Intent intent)
	{
		mStartType = intent.getIntExtra(EXTRA_SERVICE_START_TYPE, DEFAULT_START_TYPE);
	}

	private void requestCheckVersion()
	{
		PackageInfo info = SDPackageUtil.getCurrentPackageInfo();

		RequestModel model = new RequestModel();
		model.putAct("version");
		model.put("dev_type", "android");
		model.put("version", String.valueOf(info.versionCode));
		RequestCallBack<String> handler = new RequestCallBack<String>()
		{

			@Override
			public void onStart()
			{
				if (mStartType == 1)
				{
					SDDialogManager.showProgressDialog("正在检测新版本");
				}
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo)
			{
				InitActUpgradeModel model = JSON.parseObject(responseInfo.result, InitActUpgradeModel.class);
				if (!SDInterfaceUtil.isActModelNull(model))
				{
					switch (model.getResponse_code())
					{
					case 0:
						SDToast.showToast("检查新版本失败!");
						break;
					case 1:
						if (hasNewVersion(model)) // 有新版本
						{
							showDialogUpgrade(model);
						} else
						{
							if (mStartType == 1) // 用户手动检测版本
							{
								SDToast.showToast("当前已是最新版本!");
							}
						}
						break;
					default:
						break;
					}
				}
			}

			@Override
			public void onFailure(HttpException error, String msg)
			{
			}

			@Override
			public void onFinish()
			{
				SDDialogManager.hideProgressDialog();
				stopSelf();
			}
		};

		InterfaceServer.getInstance().requestInterface(model, handler);

	}

	private boolean hasNewVersion(InitActUpgradeModel model)
	{
		PackageInfo info = SDPackageUtil.getCurrentPackageInfo();
		int curVersion = info.versionCode;
		if (!TextUtils.isEmpty(model.getServerVersion()) && !TextUtils.isEmpty(model.getHasfile()) && !TextUtils.isEmpty(model.getFilename()))
		{
			initDownInfo(model);
			boolean hasfile = Integer.valueOf(model.getHasfile()) == 1 ? true : false;
			if (curVersion < mServerVersion && hasfile)
			{
				SDToast.showToast("发现新版本");
				return true;
			}
		}
		return false;
	}

	private void initDownInfo(InitActUpgradeModel model)
	{
		mDownloadUrl = model.getFilename();
		mServerVersion = Integer.valueOf(model.getServerVersion());
		mFileName = App.getApplication().getString(R.string.app_name) + "_" + mServerVersion + ".apk";
	}

	private void showDialogUpgrade(final InitActUpgradeModel model)
	{
		if (!TextUtils.isEmpty(model.getForced_upgrade()))
		{
			mIsForceUpgrade = "1".equals(model.getForced_upgrade()) ? true : false;
		}

		SDDialogConfirm dialog = new SDDialogConfirm();
		if (mIsForceUpgrade)
		{
			dialog.setTextCancel(null).setCancelable(false);
		}
		dialog.setTextContent(model.getAndroid_upgrade()).setTextTitle("新版本");
		dialog.setmListener(new SDDialogCustomListener()
		{

			@Override
			public void onDismiss(DialogInterface iDialog, SDDialogCustom dialog)
			{
			}

			@Override
			public void onClickConfirm(View v, SDDialogCustom dialog)
			{
				startDownload();
			}

			@Override
			public void onClickCancel(View v, SDDialogCustom dialog)
			{
			}
		}).show();
	}

	private void initNotification()
	{
		mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		mNotification = new Notification();
		mNotification.icon = R.drawable.icon;
		mNotification.tickerText = mFileName + "正在下载中";
		mNotification.contentView = new RemoteViews(getApplication().getPackageName(), R.layout.service_download_view);

		Intent completingIntent = new Intent();
		completingIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		completingIntent.setClass(getApplication().getApplicationContext(), AppUpgradeService.class);
		mPendingIntent = PendingIntent.getActivity(AppUpgradeService.this, R.string.app_name, completingIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		mNotification.contentIntent = mPendingIntent;

		mNotification.contentView.setTextViewText(R.id.upgradeService_tv_appname, mFileName);
		mNotification.contentView.setTextViewText(R.id.upgradeService_tv_status, "下载中");
		mNotification.contentView.setProgressBar(R.id.upgradeService_pb, 100, 0, false);
		mNotification.contentView.setTextViewText(R.id.upgradeService_tv, "0%");

		mNotificationManager.cancel(mNotificationId);
		mNotificationManager.notify(mNotificationId, mNotification);

	}

	private void startDownload()
	{
		final String target = OtherUtils.getDiskCacheDir(getApplicationContext(), "") + mFileName;
		HttpManagerX.getHttpUtils().download(mDownloadUrl, target, true, new RequestCallBack<File>()
		{

			@Override
			public void onStart()
			{
				initNotification();
			}

			@Override
			public void onLoading(long total, long current, boolean isUploading)
			{
				int progress = (int) ((current * 100) / (total));
				mNotification.contentView.setProgressBar(R.id.upgradeService_pb, 100, progress, false);
				mNotification.contentView.setTextViewText(R.id.upgradeService_tv, progress + "%");
				mNotificationManager.notify(mNotificationId, mNotification);
			}

			@Override
			public void onSuccess(ResponseInfo<File> responseInfo)
			{
				dealDownloadSuccess(responseInfo.result.getAbsolutePath());
			}

			@Override
			public void onFailure(HttpException error, String msg)
			{
				if (error != null)
				{
					if (error.getExceptionCode() == 416) // 文件已经存在
					{
						dealDownloadSuccess(target);
						return;
					}
				}
				SDToast.showToast("下载失败");
			}

		});

	}

	public void dealDownloadSuccess(String filePath)
	{
		if (!TextUtils.isEmpty(filePath))
		{
			mNotification.contentView.setViewVisibility(R.id.upgradeService_pb, View.GONE);
			mNotification.defaults = Notification.DEFAULT_SOUND;
			mNotification.contentIntent = mPendingIntent;
			mNotification.contentView.setTextViewText(R.id.upgradeService_tv_status, "下载完成");
			mNotification.contentView.setTextViewText(R.id.upgradeService_tv, "100%");
			mNotificationManager.notify(mNotificationId, mNotification);
			mNotificationManager.cancel(mNotificationId);
			SDPackageUtil.installApkPackage(filePath);
			SDToast.showToast("下载完成");
		}
	}

}